package io.renren.modules.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.enums.*;
import io.renren.modules.customer.entity.CustomerEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.customer.dao.BatchApplicationDao;
import io.renren.modules.customer.entity.BatchApplicationEntity;
import io.renren.modules.customer.service.BatchApplicationService;


@Service("batchApplicationService")
public class BatchApplicationServiceImpl extends ServiceImpl<BatchApplicationDao, BatchApplicationEntity> implements BatchApplicationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BatchApplicationServiceImpl.class);

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<BatchApplicationEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank((String) params.get("mobilePhone"))) {
            queryWrapper.eq(BatchApplicationEntity::getMobilePhone, ((String) params.get("mobilePhone")).trim());
        }
        if (StringUtils.isNotBlank((String) params.get("batchNumber"))) {
            queryWrapper.eq(BatchApplicationEntity::getBatchNumber, ((String) params.get("batchNumber")).trim());
        }
        if (StringUtils.isNotBlank((String) params.get("idNumber"))) {
            queryWrapper.eq(BatchApplicationEntity::getIdNumber, ((String) params.get("idNumber")).trim());
        }
        if (StringUtils.isNotBlank((String) params.get("name"))) {
            queryWrapper.eq(BatchApplicationEntity::getName, ((String) params.get("name")).trim());
        }

        IPage<BatchApplicationEntity> page = this.page(
                new Query<BatchApplicationEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public BatchApplicationEntity getByBatchNumberAndMobilePhone(String batchNumber, String mobilePhone) {
        if (StringUtils.isNotBlank(batchNumber) && StringUtils.isNotBlank(mobilePhone)) {
            LambdaQueryWrapper<BatchApplicationEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BatchApplicationEntity::getBatchNumber, batchNumber.trim());
            queryWrapper.eq(BatchApplicationEntity::getMobilePhone, mobilePhone.trim());
            return this.baseMapper.selectOne(queryWrapper);
        } else {
            return null;
        }
    }

    @Override
    public List<BatchApplicationEntity> submitToApply(Map<String, String> batchNumbers, List<CustomerEntity> customerEntities, Long currentUserId) {
        List<BatchApplicationEntity> applicationEntities = new ArrayList<>();
        if (customerEntities != null && customerEntities.size() > 0) {
            String batchNumber = null;
            for (CustomerEntity customerEntity : customerEntities) {
                batchNumber = batchNumbers.get(customerEntity.getMobilePhone());
                BatchApplicationEntity applicationEntity = this.getByBatchNumberAndMobilePhone(batchNumber, customerEntity.getMobilePhone());
                if (applicationEntity != null) {
                    applicationEntities.add(applicationEntity);
                    LOGGER.warn("batch number {} with mobile phone {} has been submitted", batchNumber, customerEntity.getMobilePhone());
                } else {
                    applicationEntity = new BatchApplicationEntity();
                    //设置业务字段
                    applicationEntity.setBatchNumber(batchNumber);
                    applicationEntity.setStatus(CommonProcessStatus.PENDING);
                    applicationEntity.setRequestCount(0);

                    applicationEntity.setName(customerEntity.getName());
                    applicationEntity.setMobilePhone(customerEntity.getMobilePhone());

                    applicationEntity.setCity(customerEntity.getCity());
                    applicationEntity.setChannel(customerEntity.getChannel());
                    applicationEntity.setChannelSource(customerEntity.getChannelSource());

                    applicationEntity.setLabel(customerEntity.getLabel());
                    applicationEntity.setGender(customerEntity.getGender());
                    applicationEntity.setIdNumber(customerEntity.getIdNumber());
                    applicationEntity.setBirthDay(customerEntity.getBirthDay());
                    if (applicationEntity.getBirthDay() != null) {
                        Integer age = Integer.parseInt(DateFormatUtils.format(new Date(), "yyyy")) - Integer.parseInt(DateFormatUtils.format(applicationEntity.getBirthDay(), "yyyy"));
                        if (age > 0) {
                            applicationEntity.setAge(age + 1);
                        }
                    }
                    applicationEntity.setIsHouse(customerEntity.getOwnHouse() == null ? false : customerEntity.getOwnHouse());
                    if (customerEntity.getOwnHouse() != null && customerEntity.getOwnHouse()) {
                        if (customerEntity.getHouseBuyTime() != null) {
                            Date sixMonthAgo = DateUtils.addMonths(new Date(), -6);
                            sixMonthAgo = DateUtils.truncate(sixMonthAgo, Calendar.DATE);
                            if (sixMonthAgo.compareTo(customerEntity.getHouseBuyTime()) >= 0) {
                                applicationEntity.setHousingBuyPeriod(PaHousingPeriodType.LESS_THAN_6_MONTH);
                            } else {
                                applicationEntity.setHousingBuyPeriod(PaHousingPeriodType.MORE_THAN_6_MONTH);
                            }
                        }
                    }

                    if (customerEntity.getMonthlyIncome() != null) {
                        PaMonthIncomeType incomeType = null;
                        if (customerEntity.getMonthlyIncome() < 3000) {
                            incomeType = PaMonthIncomeType.LESS_THAN_3K;
                        } else if (customerEntity.getMonthlyIncome() < 4000) {
                            incomeType = PaMonthIncomeType.LESS_THAN_4K;
                        } else if (customerEntity.getMonthlyIncome() < 5000) {
                            incomeType = PaMonthIncomeType.LESS_THAN_5K;
                        } else if (customerEntity.getMonthlyIncome() < 10000) {
                            incomeType = PaMonthIncomeType.LESS_THAN_10K;
                        } else {
                            incomeType = PaMonthIncomeType.MORE_THAN_10K;
                        }

                        applicationEntity.setMonthIncome(incomeType);
                    }

                    applicationEntity.setCarStatus(customerEntity.getOwnCar() == null ? false : customerEntity.getOwnCar());
                    applicationEntity.setCarPledgeStatus(customerEntity.getCarPledge() == null ? false : customerEntity.getCarPledge());

                    if (customerEntity.getPinganInsuranceTime() != null) {
                        Date twoYearsAgo = DateUtils.addYears(new Date(), -2);
                        twoYearsAgo = DateUtils.truncate(twoYearsAgo, Calendar.DATE);
                        if (twoYearsAgo.compareTo(customerEntity.getPinganInsuranceTime()) >= 0) {
                            applicationEntity.setPaInsuranceType(PaInsurancePeriodType.MORE_THAN_2_YEAR);
                        } else {
                            applicationEntity.setPaInsuranceType(PaInsurancePeriodType.LESS_THAN_2_YEAR);
                        }
                    }

                    if (customerEntity.getDepositPeriod() != null && customerEntity.getDepositPeriod() >= 12) {
                        applicationEntity.setDepositPeriod(DepositPeriodType.MORE_THAN_12_MONTH);
                    } else {
                        applicationEntity.setDepositPeriod(DepositPeriodType.LESS_THAN_12_MONTH);
                    }

                    //设置基本字段
                    applicationEntity.setCreateUserId(currentUserId);
                    applicationEntity.setCreateTime(new Date());

                    this.baseMapper.insert(applicationEntity);
                    applicationEntities.add(applicationEntity);
                }
            }
        }
        return applicationEntities;
    }

    @Override
    public List<BatchApplicationEntity> getPendingRequestEntities4Apply(int batchSize) {
        LambdaQueryWrapper<BatchApplicationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BatchApplicationEntity::getStatus, CommonProcessStatus.PENDING);
        queryWrapper.isNotNull(BatchApplicationEntity::getName);
        queryWrapper.isNotNull(BatchApplicationEntity::getMobilePhone);
        queryWrapper.isNotNull(BatchApplicationEntity::getCity);
        queryWrapper.orderByAsc(BatchApplicationEntity::getId);
        if (batchSize > 0) {
            queryWrapper.last(" limit " + batchSize);
        }
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<BatchApplicationEntity> getFailRequestEntities4Apply(int batchSize, int maxRetryCount) {
        if (maxRetryCount < 1) {
            return Collections.emptyList();
        } else {
            LambdaQueryWrapper<BatchApplicationEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BatchApplicationEntity::getStatus, CommonProcessStatus.FAIL);
            queryWrapper.isNotNull(BatchApplicationEntity::getName);
            queryWrapper.isNotNull(BatchApplicationEntity::getMobilePhone);
            queryWrapper.isNotNull(BatchApplicationEntity::getCity);
            queryWrapper.lt(BatchApplicationEntity::getRequestCount, maxRetryCount);
            queryWrapper.orderByAsc(BatchApplicationEntity::getId);
            if (batchSize > 0) {
                queryWrapper.last(" limit " + batchSize);
            }
            return this.baseMapper.selectList(queryWrapper);
        }
    }
}